package com.zjdiepu.www.biz.fk;

import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.GPSListStatus;
import com.zjdiepu.www.base.enums.status.InsuranceStatus;
import com.zjdiepu.www.base.enums.type.BusinessExtrasCodeType;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.commpent.RedisObjectClient;
import com.zjdiepu.www.dao.base.DpBaseDealerInfoMapper;
import com.zjdiepu.www.dao.dh.DhArchiveMapper;
import com.zjdiepu.www.dao.dh.FkInsureListMapper;
import com.zjdiepu.www.dao.dz.DzGpsListMapper;
import com.zjdiepu.www.dao.fk.FkTmpCarRecheckMapper;
import com.zjdiepu.www.dao.system.BaseBusiUnitMapper;
import com.zjdiepu.www.dao.system.BaseSalersmanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessCarMapper;
import com.zjdiepu.www.dao.yw.YwBusinessExtrasMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.ibiz.fk.IFkTmpCarRecheckService;
import com.zjdiepu.www.model.base.dto.DpBaseDealerInfo;
import com.zjdiepu.www.model.base.dto.SimpleDataDictionary;
import com.zjdiepu.www.model.dh.dto.DhArchive;
import com.zjdiepu.www.model.dh.dto.FkInsureList;
import com.zjdiepu.www.model.dh.ext.DhArchiveExt;
import com.zjdiepu.www.model.dz.dto.DzGpsList;
import com.zjdiepu.www.model.fk.dto.FkTmpCarRecheck;
import com.zjdiepu.www.model.fk.ext.FkTmpCarRecheckExt;
import com.zjdiepu.www.model.system.dto.BaseBusiUnit;
import com.zjdiepu.www.model.system.dto.BaseSalersman;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwBusinessExtras;
import com.zjdiepu.www.model.yw.ext.YwBusinessExtrasExt;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 车辆资料复审临时表Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年08月02日 10时33分<br/>
 * @since 1.0<br/>
 */
@Service
public class FkTmpCarRecheckServiceImpl extends BaseService implements IFkTmpCarRecheckService {
	public static final Logger logger = LoggerFactory.getLogger(FkTmpCarRecheckServiceImpl.class);

	@Autowired
	private BaseSalersmanMapper baseSalersmanMapper;
	@Autowired
	private BaseBusiUnitMapper baseBusiUnitMapper;
	@Autowired
	private DpBaseDealerInfoMapper dpBaseDealerInfoMapper;
	@Autowired
	private DhArchiveMapper dhArchiveMapper;
	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private YwBusinessCarMapper ywBusinessCarMapper;
	@Autowired
	private DzGpsListMapper dzGpsListMapper;
	@Autowired
	private FkInsureListMapper fkInsureListMapper;
	@Autowired
	private FkTmpCarRecheckMapper fkTmpCarRecheckMapper;
	@Autowired
	private YwBusinessExtrasMapper ywBusinessExtrasMapper;
	@Autowired
	private RedisObjectClient redisObjectClient;
	
	@Override
	public ApiResponse saveVehicleDataReview(FkTmpCarRecheck fkTmpCarRecheck,
			AbstractSysUser currentUser,Boolean commit) {
		String id = fkTmpCarRecheck.getId();
		if(StringUtils.isNotBlank(id)) {
			fkTmpCarRecheck.initUpdateData(currentUser.getId(), currentUser.getName());
			fkTmpCarRecheckMapper.updateByPrimaryKeySelective(fkTmpCarRecheck);
		} else {
			fkTmpCarRecheck.initInsertData(currentUser.getId(), currentUser.getName());
			fkTmpCarRecheckMapper.insert(fkTmpCarRecheck);
		}
		if(null != commit && commit) {
			String carId = fkTmpCarRecheck.getCarId();
			if(StringUtils.isBlank(carId)) {
				ExceptionHelper.thow("999", "车辆ID不能为空");
			}
//			String registrationId = fkTmpCarRecheck.getRegistrationId();
//			if(StringUtils.isBlank(registrationId)) {
//				ExceptionHelper.thow("999", "车牌ID不能为空");
//			}
			String busiId = fkTmpCarRecheck.getBusiId();
			YwBusiness ywBusiness = new YwBusiness();
			ywBusiness.setId(busiId);
			ywBusiness.setBusiStatus(BusiStatus.CHE_INFO_REPLAY_OK.getCode());
			ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
			
			YwBusinessCar ywBusinessCar = new YwBusinessCar();
			BeanUtils.copyProperties(fkTmpCarRecheck, ywBusinessCar);
			ywBusinessCar.setId(fkTmpCarRecheck.getCarId());
			//@update 2017-12-06 防止被修改
			ywBusinessCar.setPrice(null);
			ywBusinessCar.setCusId(null);
			ywBusinessCarMapper.updateByPrimaryKeySelective(ywBusinessCar);
			
//			DzRegistration dzRegistration = new DzRegistration();
//			BeanUtils.copyProperties(fkTmpCarRecheck, dzRegistration);
//			dzRegistrationMapper.updateByPrimaryKey(dzRegistration);
			
			//带投保列表
			YwBusiness dbYwBusiness = ywBusinessMapper.selectByPrimaryKey(busiId);
			String customerId = dbYwBusiness.getCustomerId();
			String customerName = dbYwBusiness.getCustomerName();
			String customerNo = dbYwBusiness.getCustomerNo();
			
			FkInsureList fkInsureList = new FkInsureList();
			fkInsureList.initInsertData(currentUser.getId(), currentUser.getName());
			fkInsureList.setCusId(customerId);
			fkInsureList.setBusiId(busiId);
			fkInsureList.setLoanAmount(dbYwBusiness.getRealLoanAmount());
			String channelType = dbYwBusiness.getChannelType();
			fkInsureList.setChannelType(channelType);
			
			fkInsureList.setCusName(customerName);
			fkInsureList.setCusIdno(customerNo);
			String salesmanId = dbYwBusiness.getSalesmanId();
			BaseSalersman baseSalersman = baseSalersmanMapper.selectByPrimaryKey(salesmanId);
			fkInsureList.setSalersmanName(baseSalersman.getName());
			String unitId = baseSalersman.getUnitId();
			BaseBusiUnit baseBusiUnit = baseBusiUnitMapper.selectByPrimaryKey(unitId);
			fkInsureList.setDepartmentName(baseBusiUnit.getOrgName());
			String dealerId = dbYwBusiness.getDealerId();
			DpBaseDealerInfo dpBaseDealerInfo = dpBaseDealerInfoMapper.selectByPrimaryKey(dealerId);
			fkInsureList.setDealer(dpBaseDealerInfo.getDealerName());
			
			DhArchiveExt dhArchiveExt = new DhArchiveExt();
			dhArchiveExt.setBusiId(busiId);
			dhArchiveExt.setRows(1);
			List<DhArchive> dhArchives = dhArchiveMapper.selectByExt(dhArchiveExt);	
			if(CollectionUtils.isNotEmpty(dhArchives)) {
				DhArchive dhArchive = dhArchives.get(0);
				fkInsureList.setNoRecord(dhArchive.getNoRecord());
			}
			
			//GPS待加装列表
			YwBusinessExtrasExt ywBusinessExtrasExt = new YwBusinessExtrasExt();
			ywBusinessExtrasExt.setBaseWhere();
			ywBusinessExtrasExt.setRows(1);
			ywBusinessExtrasExt.setTypeExtras(BusinessExtrasCodeType.ADD_GPS.getCode());
			ywBusinessExtrasExt.setBusiId(busiId);
			List<YwBusinessExtras> ywBusinessExtrases = ywBusinessExtrasMapper.selectByExt(ywBusinessExtrasExt);
			YwBusinessExtras ywBusinessExtras = null;
			if(CollectionUtils.isNotEmpty(ywBusinessExtrases)) {
				ywBusinessExtras = ywBusinessExtrases.get(0);
			}
			DzGpsList dzGpsList = new DzGpsList();
			dzGpsList.setBusiId(busiId);
			dzGpsList.setDpStatus(DpStatus.NORMAL.getCode());
			int hasCount = dzGpsListMapper.countRefined(dzGpsList);
			int valueExtra = 0;
			if(null != ywBusinessExtras && hasCount == 0) {
				String valueExtras = ywBusinessExtras.getValueExtras();
				if(StringUtils.isNotBlank(valueExtras)) {
					try {
						valueExtra = Integer.parseInt(valueExtras.trim());
						if(valueExtra != 0) {
							dzGpsList.initInsertData(currentUser.getId(), currentUser.getName());
							
							dzGpsList.setNumGps(valueExtra);
							dzGpsList.setLoanAmount(dbYwBusiness.getRealLoanAmount());
							dzGpsList.setChannelType(dbYwBusiness.getChannelType());
							dzGpsList.setDealer(dpBaseDealerInfo.getDealerName());
							dzGpsList.setDepartmentName(baseBusiUnit.getOrgName());
							dzGpsList.setSalersmanName(baseSalersman.getName());
							dzGpsList.setCusName(customerName);
							dzGpsList.setCusIdno(customerNo);
						}
					} catch (NumberFormatException e) {
						//不是数字,不需要待加装GPS
						valueExtra = 0;
					}
				}
			}
			
			redisObjectClient.execute(new RedisCallback<Boolean>() {
				@Override
				public Boolean doInRedis(RedisConnection redisConnection)
						throws DataAccessException {
					String dealerLevel = dpBaseDealerInfo.getDealerLevel();
					SimpleDataDictionary simpleDataDictionary = redisObjectClient.hGet(redisConnection, SimpleDataDictionary.class.getSimpleName(), dealerLevel, DataDicType.DEALER_LEVEL.getCode());
					String bankLoan = dbYwBusiness.getBankLoan();
					SimpleDataDictionary simpleDataDictionary1 = redisObjectClient.hGet(redisConnection, SimpleDataDictionary.class.getSimpleName(), bankLoan, DataDicType.LOAN_BANK.getCode());
					SimpleDataDictionary simpleDataDictionary2 = redisObjectClient.hGet(redisConnection, SimpleDataDictionary.class.getSimpleName(), channelType, DataDicType.CHANNEL_TYPE.getCode());
					
					fkInsureList.setDealerLevel(simpleDataDictionary.getName());
					fkInsureList.setBankname(simpleDataDictionary1.getName());
					fkInsureList.setChannelTypeName(simpleDataDictionary2.getName());
					
					dzGpsList.setDealerLevel(simpleDataDictionary.getName());
					dzGpsList.setBankname(simpleDataDictionary1.getName());
					dzGpsList.setChannelTypeName(simpleDataDictionary2.getName());
					return true;
				}
			});
			
			if(valueExtra != 0 && hasCount == 0) {
				dzGpsList.setStatusGpsList(GPSListStatus.WEI_TI_JIAO.getCode());
				dzGpsListMapper.insert(dzGpsList);
			}
			
			fkInsureList.setInsuranceStatus(InsuranceStatus.DAI_BAO.getCode());
			fkInsureListMapper.insert(fkInsureList);
		}
		return ApiResponse.success(fkTmpCarRecheck.getId());
	}
	
	@Override
	public void saveUpdateAndDelete(FkTmpCarRecheck fkTmpCarRecheck, OperateType operType) {
		switch (operType) {
		case add:
			fkTmpCarRecheck.initInsertData(fkTmpCarRecheck.getModifier(), fkTmpCarRecheck.getModifierName());
			fkTmpCarRecheckMapper.insert(fkTmpCarRecheck);
			break;
		case edit:
			fkTmpCarRecheck.initUpdateData(fkTmpCarRecheck.getModifier(), fkTmpCarRecheck.getModifierName());
			// 影响的记录数
			int updateCount = fkTmpCarRecheckMapper.updateByPrimaryKeySelective(fkTmpCarRecheck);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			fkTmpCarRecheck.initDeleteData(fkTmpCarRecheck.getModifier(), fkTmpCarRecheck.getModifierName());
			// 影响的记录数
			int deleteCount = fkTmpCarRecheckMapper.updateByPrimaryKeySelective(fkTmpCarRecheck);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<FkTmpCarRecheck> selectByExt(FkTmpCarRecheckExt fkTmpCarRecheckExt) {
		return fkTmpCarRecheckMapper.selectByExt(fkTmpCarRecheckExt);
	}
	
	@Override
	public int countByExt(FkTmpCarRecheckExt fkTmpCarRecheckExt){
		return fkTmpCarRecheckMapper.countByExt(fkTmpCarRecheckExt);
	}
	
	@Override
	public FkTmpCarRecheck selectById(String id) {
		return fkTmpCarRecheckMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			fkTmpCarRecheckMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(FkTmpCarRecheck fkTmpCarRecheck) {
		return fkTmpCarRecheckMapper.countRefined(fkTmpCarRecheck);
	}

	@Override
	public FkTmpCarRecheck selectRefined(FkTmpCarRecheck fkTmpCarRecheck) {
		return fkTmpCarRecheckMapper.selectRefined(fkTmpCarRecheck);
	}
	
	@Override
	public int deletedRefined(FkTmpCarRecheck fkTmpCarRecheck) {
		return fkTmpCarRecheckMapper.deletedRefined(fkTmpCarRecheck);
	}

	@Override
	public boolean repeat(FkTmpCarRecheck fkTmpCarRecheck) {
		int count = countRefined(fkTmpCarRecheck);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(fkTmpCarRecheck.getId())) {
			return true;
		}
		FkTmpCarRecheck dbItem = selectRefined(fkTmpCarRecheck);
		if(null == dbItem) {
			return false;
		}
		return !fkTmpCarRecheck.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return fkTmpCarRecheckMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<FkTmpCarRecheck> fkTmpCarRechecks) {
		return fkTmpCarRecheckMapper.insertBatch(fkTmpCarRechecks);
	}
}
